package com.yxj.securityhello.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.security.Keys;

/**
 * @author yangxuejiao
 * @description
 * @createDate 2025/11/2 14:55
 */
public class JwtUtils {
    //jwt有效期
    public static final Long JWT_TTL = 1000L * 60 * 60; //1h
    //jwt密钥(盐)
    public static final String JWT_KEY = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO123456f";
    //生成令牌
    public static String getUUID() {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }

    /**
     * 生成jwt
     * @param subject token中要存储的数据（json格式）用户数据
     * @param ttlMillis ttlMillis token超时时间
     * @return
     */
    public static String createJwt(String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject,ttlMillis,getUUID()); // 设置过期时间
        return builder.compact();
    }

    /**
     * 生成Jwt的业务逻辑代码
     */
    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis==null){
            ttlMillis = JwtUtils.JWT_TTL;
        }

        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid) //唯一的ID
                .setSubject(subject) // 主题  可以是JSON数据
                .setIssuer("yeqing") // 签发者
                .setIssuedAt(now) // 签发时间
                .signWith(signatureAlgorithm, secretKey) // 签名算法以及密匙
                .setExpiration(expDate);
    }

    public static String createJwt(String id, String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject,ttlMillis,id); // 设置过期时间
        return builder.compact();
    }

    /**
     * 生成加密后的密钥 secretKey
     */
    public static SecretKey generalKey() {
//        byte[] encodedKey = Base64.getDecoder().decode(JwtUtils.JWT_KEY);
        return Keys.hmacShaKeyFor(JwtUtils.JWT_KEY.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 解析Jwt
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
}
